package com.zoro.barn.commons.db.autopage;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.zoro.barn.commons.foundation.web.FeignRequestEncoder;
import com.zoro.barn.commons.foundation.web.PageRequestInterface;
import com.zoro.barn.commons.tools.json.JsonUtil;

import java.lang.reflect.Type;

/**
 * @author zhaoxingwu
 */
public class PagingFeignRequestEncoder implements FeignRequestEncoder {

    private final String currentPageKey;
    private final String pageSizeKey;

    public PagingFeignRequestEncoder(String currentPageKey, String pageSizeKey) {
        this.currentPageKey = currentPageKey;
        this.pageSizeKey = pageSizeKey;
    }

    @Override
    public Object encode(Object object, Type bodyType, Object oriObject) throws JsonProcessingException {

        if (bodyType instanceof Class<?>
                && PageRequestInterface.class.isAssignableFrom((Class<?>) bodyType)){
            int current;
            int pageSize;
            ObjectNode data;
            if (object != null) {
                PageRequestInterface requestData = (PageRequestInterface) object;
                if (requestData.isPage()) {
                    pageSize = requestData.getPageSize();
                    current = requestData.getCurrent();
                    data = JsonUtil.readJsonObject(JsonUtil.toString(object));
                    // 这两个属性没有用了
                    data.remove("pageSize");
                    data.remove("current");
                    data.put(this.currentPageKey, current);
                    data.put(this.pageSizeKey, pageSize);
                    return data.toString();
                }else {
                    return object;
                }
            } else {
                return null;
            }
        } else {
            return object;
        }
    }
}
